@file:OptIn(ExperimentalMaterial3Api::class)

package wang.xinqiu.mysqlcontrol.ui

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import wang.xinqiu.mysqlcontrol.data.MySQLManager

data class TableField(
    var name: String = "",
    var type: String = "VARCHAR",
    var length: String = "255",
    var nullable: Boolean = true,
    var primaryKey: Boolean = false,
    var autoIncrement: Boolean = false,
    var defaultValue: String = "",
    var comment: String = ""
)

@Composable
fun TableDesignScreen(
    databaseName: String,
    tableName: String? = null, // null表示创建新表
    mysqlManager: MySQLManager,
    onBack: () -> Unit,
    onSessionExpired: (() -> Unit)? = null
) {
    val context = LocalContext.current
    val isEditMode = tableName != null
    
    var currentTableName by remember { mutableStateOf(tableName ?: "") }
    var fields by remember { mutableStateOf(listOf(TableField())) }
    var isLoading by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var showSaveDialog by remember { mutableStateOf(false) }
    
    // 如果是编辑模式，加载现有表结构
    LaunchedEffect(tableName) {
        if (isEditMode && tableName != null) {
            isLoading = true
            val result = mysqlManager.executeQuery(databaseName, "DESCRIBE `$tableName`")
            if (result.isSuccess) {
                val queryResult = result.getOrNull()
                fields = queryResult?.rows?.map { row ->
                    TableField(
                        name = row[0],
                        type = row[1].split("(")[0].uppercase(),
                        length = if (row[1].contains("(")) row[1].substringAfter("(").substringBefore(")") else "",
                        nullable = row[2] == "YES",
                        primaryKey = row[3] == "PRI",
                        autoIncrement = row[5].contains("auto_increment"),
                        defaultValue = row[4].takeIf { it != "NULL" } ?: ""
                    )
                } ?: listOf(TableField())
            }
            isLoading = false
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (isEditMode) "设计表 - $tableName" else "创建新表") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(
                        onClick = { showSaveDialog = true },
                        enabled = currentTableName.isNotBlank() && fields.any { it.name.isNotBlank() }
                    ) {
                        Icon(Icons.Default.Save, contentDescription = "保存")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            if (!isEditMode) {
                OutlinedTextField(
                    value = currentTableName,
                    onValueChange = { currentTableName = it },
                    label = { Text("表名") },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = !isLoading
                )
                Spacer(modifier = Modifier.height(16.dp))
            }
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "字段设计",
                    style = MaterialTheme.typography.titleMedium
                )
                
                IconButton(
                    onClick = {
                        fields = fields + TableField()
                    }
                ) {
                    Icon(Icons.Default.Add, contentDescription = "添加字段")
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            if (isLoading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else {
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    itemsIndexed(fields) { index, field ->
                        FieldDesignCard(
                            field = field,
                            onFieldChange = { updatedField ->
                                fields = fields.toMutableList().apply {
                                    this[index] = updatedField
                                }
                            },
                            onDelete = {
                                if (fields.size > 1) {
                                    fields = fields.toMutableList().apply {
                                        removeAt(index)
                                    }
                                }
                            },
                            canDelete = fields.size > 1
                        )
                    }
                }
            }
            
            errorMessage?.let { error ->
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Text(
                        text = "错误: $error",
                        modifier = Modifier.padding(16.dp),
                        color = MaterialTheme.colorScheme.onErrorContainer
                    )
                }
            }
        }
    }
    
    // 保存确认对话框
    if (showSaveDialog) {
        AlertDialog(
            onDismissRequest = { showSaveDialog = false },
            title = { Text(if (isEditMode) "保存表结构" else "创建表") },
            text = { 
                Text(
                    if (isEditMode) 
                        "确定要保存对表 '$tableName' 的修改吗？" 
                    else 
                        "确定要创建表 '$currentTableName' 吗？"
                ) 
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        showSaveDialog = false
                        isLoading = true
                        errorMessage = null
                        
                        (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                            val sql = generateCreateTableSQL(
                                if (isEditMode) tableName!! else currentTableName,
                                fields,
                                isEditMode
                            )
                            
                            val result = mysqlManager.executeQuery(databaseName, sql)
                            isLoading = false
                            
                            if (result.isSuccess) {
                                onBack()
                            } else {
                                errorMessage = result.exceptionOrNull()?.message
                                if (errorMessage?.contains("会话已过期") == true) {
                                    onSessionExpired?.invoke()
                                }
                            }
                        }
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(onClick = { showSaveDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun FieldDesignCard(
    field: TableField,
    onFieldChange: (TableField) -> Unit,
    onDelete: () -> Unit,
    canDelete: Boolean
) {
    var expanded by remember { mutableStateOf(false) }
    
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = field.name.ifBlank { "新字段" },
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.weight(1f)
                )
                
                Row {
                    IconButton(onClick = { expanded = !expanded }) {
                        Icon(
                            if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
                            contentDescription = if (expanded) "收起" else "展开"
                        )
                    }
                    
                    if (canDelete) {
                        IconButton(onClick = onDelete) {
                            Icon(Icons.Default.Delete, contentDescription = "删除字段")
                        }
                    }
                }
            }
            
            if (expanded) {
                Spacer(modifier = Modifier.height(16.dp))
                
                // 字段名
                OutlinedTextField(
                    value = field.name,
                    onValueChange = { onFieldChange(field.copy(name = it)) },
                    label = { Text("字段名") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 数据类型
                    var showTypeDropdown by remember { mutableStateOf(false) }
                    val dataTypes = listOf(
                        "VARCHAR", "INT", "BIGINT", "TEXT", "DATETIME", 
                        "DATE", "TIME", "DECIMAL", "FLOAT", "DOUBLE",
                        "BOOLEAN", "TINYINT", "SMALLINT", "MEDIUMINT"
                    )
                    
                    Box(modifier = Modifier.weight(1f)) {
                        OutlinedTextField(
                            value = field.type,
                            onValueChange = { },
                            label = { Text("类型") },
                            readOnly = true,
                            modifier = Modifier.fillMaxWidth(),
                            trailingIcon = {
                                IconButton(onClick = { showTypeDropdown = true }) {
                                    Icon(Icons.Default.ArrowDropDown, contentDescription = null)
                                }
                            }
                        )
                        
                        DropdownMenu(
                            expanded = showTypeDropdown,
                            onDismissRequest = { showTypeDropdown = false }
                        ) {
                            dataTypes.forEach { type ->
                                DropdownMenuItem(
                                    text = { Text(type) },
                                    onClick = {
                                        onFieldChange(field.copy(type = type))
                                        showTypeDropdown = false
                                    }
                                )
                            }
                        }
                    }
                    
                    // 长度
                    if (field.type in listOf("VARCHAR", "CHAR", "DECIMAL")) {
                        OutlinedTextField(
                            value = field.length,
                            onValueChange = { onFieldChange(field.copy(length = it)) },
                            label = { Text("长度") },
                            modifier = Modifier.weight(0.5f),
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 约束选项
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Checkbox(
                            checked = field.primaryKey,
                            onCheckedChange = { onFieldChange(field.copy(primaryKey = it)) }
                        )
                        Text("主键")
                    }
                    
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Checkbox(
                            checked = !field.nullable,
                            onCheckedChange = { onFieldChange(field.copy(nullable = !it)) }
                        )
                        Text("非空")
                    }
                    
                    if (field.type in listOf("INT", "BIGINT", "TINYINT", "SMALLINT", "MEDIUMINT")) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Checkbox(
                                checked = field.autoIncrement,
                                onCheckedChange = { onFieldChange(field.copy(autoIncrement = it)) }
                            )
                            Text("自增")
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 默认值
                OutlinedTextField(
                    value = field.defaultValue,
                    onValueChange = { onFieldChange(field.copy(defaultValue = it)) },
                    label = { Text("默认值") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 注释
                OutlinedTextField(
                    value = field.comment,
                    onValueChange = { onFieldChange(field.copy(comment = it)) },
                    label = { Text("注释") },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}

private fun generateCreateTableSQL(
    tableName: String,
    fields: List<TableField>,
    isEditMode: Boolean
): String {
    if (isEditMode) {
        // 编辑模式：生成ALTER TABLE语句（简化版本）
        return "-- 表结构修改功能开发中，请使用SQL查询手动修改"
    } else {
        // 创建模式：生成CREATE TABLE语句
        val fieldDefinitions = fields.filter { it.name.isNotBlank() }.map { field ->
            buildString {
                append("`${field.name}` ${field.type}")
                
                if (field.length.isNotBlank() && field.type in listOf("VARCHAR", "CHAR", "DECIMAL")) {
                    append("(${field.length})")
                }
                
                if (!field.nullable) append(" NOT NULL")
                if (field.autoIncrement) append(" AUTO_INCREMENT")
                if (field.defaultValue.isNotBlank()) append(" DEFAULT '${field.defaultValue}'")
                if (field.comment.isNotBlank()) append(" COMMENT '${field.comment}'")
            }
        }
        
        val primaryKeys = fields.filter { it.primaryKey && it.name.isNotBlank() }
        
        return buildString {
            appendLine("CREATE TABLE `$tableName` (")
            appendLine(fieldDefinitions.joinToString(",\n") { "  $it" })
            if (primaryKeys.isNotEmpty()) {
                appendLine(",")
                appendLine("  PRIMARY KEY (${primaryKeys.joinToString(", ") { "`${it.name}`" }})")
            }
            append(");")
        }
    }
}